package com.example.servlet.user;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@WebServlet("/ChatServlet")
public class ChatServlet extends HttpServlet {
    private static final String API_KEY = "sk-bb1ecf703fb943b79f560c17d8758415"; // 请替换为实际有效的 API 密钥
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain;charset=UTF-8");

        String userMessage = req.getParameter("message");
        System.out.println("接收到的消息: " + userMessage);

        if (userMessage == null || userMessage.trim().isEmpty()) {
            resp.getWriter().write("消息内容不能为空");
            return;
        }

        HttpURLConnection conn = null;
        try {
            String requestBody = buildPlainTextRequest(userMessage);
            URL url = new URL(API_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
            conn.setDoOutput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(requestBody.getBytes(StandardCharsets.UTF_8));
            }

            if (conn.getResponseCode() == 200) {
                String answer = parsePlainTextResponse(conn);

                // 检查是否包含无关内容
                if (!answer.contains("花龙腾航") && !answer.contains("对不起")) {
                    answer = "对不起，我仅能回答与花龙腾航相关的问题，请问有什么可以帮您？";
                }

                resp.getWriter().write(answer);
            } else {
                resp.getWriter().write("服务请求失败（API状态码：" + conn.getResponseCode() + "）");
            }
        } catch (Exception e) {
            resp.getWriter().write("系统处理异常：" + e.getClass().getSimpleName());
        } finally {
            if (conn != null) conn.disconnect();
        }
    }

    // 构建 JSON 请求体
    private String buildPlainTextRequest(String userMessage) {
        String systemPrompt = """
                你是花龙腾航(一个航空订票网站)的智能客服，仅回答与花龙腾航相关的问题。生成的问题保持层次清晰分点回答、逻辑严谨
                可回答的范围包括：机票预订、会员服务、航班信息、优惠活动等。自己发挥内容，但是要保证每次用户输入相同问题时要保持一致
                对于其他无关问题，请回复：'对不起，我仅能回答与花龙腾航相关的问题，请问有什么可以帮您？'""";

        return String.format(
                "{\"model\":\"deepseek-chat\",\"messages\":[" +
                        "{\"role\":\"system\",\"content\":\"%s\"}," +
                        "{\"role\":\"user\",\"content\":\"%s\"}]," +
                        "\"temperature\":0.7}",
                escapeJson(systemPrompt),
                escapeJson(userMessage)
        );
    }

    // 转义 JSON 字符串
    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r");
    }

    // 解析 API 响应
    private String parsePlainTextResponse(HttpURLConnection conn) throws IOException {
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {

            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }

            int start = response.indexOf("\"content\":\"") + 11;
            if (start < 11) return "响应解析失败";
            int end = response.indexOf("\"", start);
            if (end <= start) return "响应格式异常";

            return response.substring(start, end)
                    .replace("\\n", "\n")
                    .replace("\\\"", "\"");
        }
    }
}
